#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
Created on 2011-11-11

@author: zhongfeng
'''
from itertools import chain
import os 
from dbproc.basedbproc import getCatBySiteIdAndLevel,getAllWebsiteBaseInfo,seEncode

def createSiteCat(site_id):
    catDict = {}
    for level in xrange(0,3):
        catLevelRet = getCatBySiteIdAndLevel(site_id, level)
        catDict.update(((int(it[0]),it[1]) for it in catLevelRet))
    finalLevelRet = getCatBySiteIdAndLevel(site_id, 3)
    result = []
    for t in finalLevelRet:
        tr = [seEncode(it, encoding='gb18030') for it in chain([(pId,catDict[int(pId)]) for pId in eval(t[-1])],(t[1],t[0],os.linesep))]
        result.append( '|'.join([s.replace('|',' ') for s in tr]))
        #result.append(os.linesep)
    return result

if __name__ == '__main__':
    baseDir = r'c:\catinfo'
    if not os.path.exists(baseDir):
        os.makedirs(baseDir)
    for en_name,id in getAllWebsiteBaseInfo():
        print en_name,id
        fName = os.path.join(baseDir,en_name)
        result = createSiteCat(id)
        with open(fName,'w') as output:
            output.writelines(result)
